package org.farm2.main.cecurity.config;

import org.apache.commons.lang3.StringUtils;
import org.farm2.base.password.FarmPasswordEncoder;
import org.farm2.main.cecurity.filter.JwtAuthenticationTokenFilter;
import org.farm2.main.exceptions.handle.SecurityAccessExceptionHandler;
import org.farm2.main.exceptions.handle.SecurityAuthExceptionPoint;
import org.farm2.tools.config.Farm2ConfigEnum;
import org.farm2.tools.config.Farm2ConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;


@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Autowired
    private UserDetailsService farmUserDetailsServiceImpl;
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;






    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {

        return authenticationConfiguration.getAuthenticationManager();
    }


    private final SecurityAuthExceptionPoint securityAuthExceptionPoint;
    private final SecurityAccessExceptionHandler securityAccessExceptionHandler;

    public SecurityConfig(SecurityAuthExceptionPoint jwtAuthenticationEntryPoint, SecurityAccessExceptionHandler jwtAccessDeniedHandler) {
        this.securityAuthExceptionPoint = jwtAuthenticationEntryPoint;
        this.securityAccessExceptionHandler = jwtAccessDeniedHandler;
    }


    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        if (StringUtils.isNotBlank(Farm2ConfigUtils.getInstance(Farm2ConfigEnum.FARM2_PROPERTIES).getData("farm2.conf.web.domain.able.url"))) {

            configuration.setAllowedOrigins(Farm2ConfigUtils.getInstance(Farm2ConfigEnum.FARM2_PROPERTIES).getDatas("farm2.conf.web.domain.able.url"));// 替换为前端的实际域名
        }

        configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(List.of("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.csrf(csrf -> csrf.disable()).cors(cors -> cors.configurationSource(corsConfigurationSource()))

                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))

                .headers(headers -> headers.frameOptions(frameOptions -> frameOptions.sameOrigin()))

                .authorizeHttpRequests(authorize -> authorize

                        .requestMatchers("/api/wfile/**").permitAll()

                        .requestMatchers("/api/current/config").permitAll()

                        .requestMatchers("/api/wchat/**").permitAll()

                        .requestMatchers("/api/process/**").permitAll()

                        .requestMatchers("/api/wtag/**").permitAll()

                        .requestMatchers("/api/search/**").permitAll()

                        .requestMatchers("/api/wknow/**").permitAll()

                        .requestMatchers("/api/login/**").permitAll()

                        .requestMatchers("/apidoc/**").permitAll()

                        .requestMatchers("/v3/api-docs/**").permitAll()

                        .requestMatchers("/api/files/download/**").permitAll()

                        .requestMatchers("/api/exfiles/download/**").permitAll()

                        .anyRequest().authenticated());

        http.exceptionHandling(exception -> exception

                .authenticationEntryPoint(securityAuthExceptionPoint)

                .accessDeniedHandler(securityAccessExceptionHandler)
        );

        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }
}
